% [Q R] = POLYDIV(N,D) Evaluate the quotient N / D
%
%   Inputs:
%
%       n    Polynomial numerator
%       d    Polynomial denominator
%
%   Outputs:
%
%       q    The quotient n / d
%       r    The remainder of n / d
%
%   Notes:
%
%       Uses pseudocode taken from 
%       http://rosettacode.org/wiki/Polynomial_long_division#Octave

function [q r] = polyDiv(n,d)

    % If the denominator is zero, throw an error
    if polyIsZero(d)
        error('Polynomial divide by zero');
    end

    % If the numerator is zero, return zero
    if polyIsZero(n)
        q = -1;
        r = -1;
        return;
    end

    % Divide n / d.

    if deg(n) >= deg(d)
        q = -1 * ones(1,deg(n) + 1);
        while (deg(n) >= deg(d))
            dd = [-1*ones(1,deg(n) - deg(d)) d];
            q(deg(n) - deg(d) + 1) = elementDiv(n(deg(n)+1),dd(deg(dd)+1));
            dd = polyMult(dd, q(deg(n) - deg(d) + 1));
            n = polyAdd(n,dd);
        end
        r = n;
    else
        q = -1;
        r = n;
    end
    q = polyTrimZeros(q);
    r = polyTrimZeros(r);
end


% Helper function: evaluate the degree of a polynomial p
function d = deg(p)

    if polyIsZero(p)
        d = -1;
        return;
    end
    p = polyTrimZeros(p);
    d = length(p) - 1; 

end
